"""任务提示词加载器."""

from __future__ import annotations

from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Any, Dict, Optional

import yaml


BASE_DIR = Path(__file__).resolve().parent.parent.parent
TASKS_FILE = BASE_DIR / "tasks.yaml"


@dataclass(frozen=True)
class TaskTemplate:
    """封装 tasks.yaml 中单个任务的描述."""

    name: str
    description: str
    expected_output: Optional[str]
    agent: Optional[str]


class TaskPromptNotFoundError(FileNotFoundError):
    """找不到任务提示词时抛出."""


@lru_cache(maxsize=None)
def load_tasks() -> Dict[str, Any]:
    """加载 tasks.yaml 中的所有任务配置."""

    if not TASKS_FILE.exists():
        raise TaskPromptNotFoundError(f"未找到任务配置文件: {TASKS_FILE}")
    with TASKS_FILE.open("r", encoding="utf-8") as fp:
        data = yaml.safe_load(fp)
    if not isinstance(data, dict):
        raise ValueError("tasks.yaml 内容格式不正确，应为字典结构")
    return data


def load_task_template(task_name: str) -> TaskTemplate:
    """获取指定任务的完整模板."""

    tasks = load_tasks()
    if task_name not in tasks:
        raise TaskPromptNotFoundError(f"在 tasks.yaml 中未找到任务 {task_name}")

    task = tasks[task_name]
    description = task.get("description")
    if not isinstance(description, str):
        raise ValueError(f"任务 {task_name} 的 description 字段缺失或格式不正确")

    expected_output = task.get("expected_output")
    if expected_output is not None and not isinstance(expected_output, str):
        raise ValueError(f"任务 {task_name} 的 expected_output 字段格式不正确")

    agent = task.get("agent")
    if agent is not None and not isinstance(agent, str):
        raise ValueError(f"任务 {task_name} 的 agent 字段格式不正确")

    return TaskTemplate(
        name=task_name,
        description=description.strip(),
        expected_output=expected_output.strip() if isinstance(expected_output, str) else None,
        agent=agent,
    )
